/**
 * 
 */
package com.asset.salesforce.controller.ajax;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.domain.Account;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Lead;
import com.asset.salesforce.dto.search.BasicSearchDTO;
import com.asset.salesforce.dto.table.ContactData;
import com.asset.salesforce.dto.table.ReadOperationParams;
import com.asset.salesforce.dto.table.ReadOperationResults;
import com.asset.salesforce.service.AccountService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.LeadService;

// TODO: Auto-generated Javadoc
/**
 *
 * @author Hisham Mounir
 * this controller class is used to handle contact requests
 */
@Controller
public class ContactRestController {
	
	/** The lead service. */
	@Autowired
	private LeadService leadService;
	
	/** The account service. */
	@Autowired
	private AccountService accountService;
	
	/** The contact service. */
	@Autowired
	private ContactService contactService;
	
	
	/**
	 * Basic search list.
	 *
	 * @param model the model
	 * @param session the session
	 * @param request the request
	 * @param query the query
	 * @param parentType the parent type
	 * @return the list
	 */
	@RequestMapping(value = "/contactCompanies", method = RequestMethod.GET,produces = "application/json")
	public @ResponseBody List<BasicSearchDTO> basicSearchList(Model model, HttpSession session,HttpServletRequest request , 
			@RequestParam String query,@RequestParam String parentType){
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		List<BasicSearchDTO>b = new ArrayList<BasicSearchDTO>();
		List<Lead>leads = new ArrayList<Lead>();
		List<Account>accounts = new ArrayList<Account>();
		if(userDetails.getIsOwner()==true){
			leads=leadService.getAllLeadsForCompany(query,userDetails.getCompany().getCompanyName());
			accounts=accountService.getAllAccountsForCompany(query,userDetails.getCompany().getId());
			}
			else{
			leads=leadService.getAllLeadsForEmployee(query,userDetails.getId());
			accounts=accountService.getAllAccountsForEmployee(query,userDetails.getId());
		}
		if(parentType.equals("lead")){
			if(leads.size()>0){
				for (Lead lead : leads) {
					BasicSearchDTO basicSearchDTO = new BasicSearchDTO();
					basicSearchDTO.setId(lead.getId());
					basicSearchDTO.setName(lead.getfName());
					basicSearchDTO.setParentCompany(lead.getCompanyName());
					basicSearchDTO.setParentType("lead");
					b.add(basicSearchDTO);
				}
			}
		}
		else{
			if(accounts.size()>0){
				for (Account account : accounts) {
					BasicSearchDTO basicSearchDTO = new BasicSearchDTO();
					basicSearchDTO.setId(account.getId());
					basicSearchDTO.setName(account.getAccountName());
					basicSearchDTO.setParentCompany(account.getCompanyName());
					basicSearchDTO.setParentType("account");
					b.add(basicSearchDTO);
				}
			}
		}
		return b;
	}
	
	/**
	 * Contacts table List.
	 *
	 * @param params the params
	 * @param session the session
	 * @return the read operation results
	 */
	@RequestMapping(value = "/contactsList", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	ReadOperationResults list(ReadOperationParams params,HttpSession session) {
		ReadOperationResults result = new ReadOperationResults();
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		
		String sortDir = params.getsSortDir_0();
		String sortColName = params.getsColumns().split(",")[params.getiSortCol_0()];
		String column=null;
		if(sortColName.equals("id")){
			column="id";
		}
		if(sortColName.equals("contactName")){
			column="fName";
		}
		if(sortColName.equals("contactCompany")){
			column="parentName";
		}
		if(sortColName.equals("mobile")){
			column="mobile";
		}
		
		List<Contact>allLeads = new ArrayList<Contact>();
		if(userDetails.getIsOwner()==true){
			allLeads = contactService.getAllContactByCompany(params.getsSearch(),userDetails.getCompany().getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = contactService.getAllSizeForOwner(params.getsSearch(),userDetails.getCompany().getCompanyName());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}
		else{
			allLeads = contactService.getAllContactByEmployee(params.getsSearch(),userDetails.getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = contactService.getAllSizeForEmployee(params.getsSearch(),userDetails.getId());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}        
        result.setsEcho(params.getsEcho());
        List<ContactData>leadData = new ArrayList<ContactData>();
		for (Contact lead : allLeads) {
			ContactData data = new ContactData();
			data.setId(lead.getId());
			data.setContactCompany(lead.getParentName());
			data.setContactName(lead.getfName());
			data.setMobile(lead.getMobile());
			leadData.add(data);
		}
        result.setAaData(leadData);
        return result;
	}
	
	/**
	 * Delete.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param id the id
	 * @return true, if successful
	 */
	@RequestMapping(value = "/deleteContact", method = RequestMethod.POST)
	@ResponseBody
	public boolean delete(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer id) {
		if (SecurityUtils.getSubject().hasRole("contactDelete")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			Contact contact = contactService.getById(id);
			contact.setIsDeleted(true);
			contact.setDateModified(new Date());
			contactService.saveOrupdate(contact);
			response.setStatus(HttpServletResponse.SC_OK);
				return true;
			}
			else{
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return false;
			}	
	}
}
